﻿@using System.Web
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>职称设置</title>
    <script src="~/lib/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css">
    <script src="//unpkg.com/element-plus"></script>
    <style>
        body {
            background-color: #FFFFCC;
        }

        .solid-table {
            border-collapse: collapse;
            width: 100%;
        }

            .solid-table td {
                border: 1px solid #333;
                padding: 8px;
                text-align: left;
            }

        .bj {
            background-color: #FFD553;
        }

        .kuan {
            width: 240px;
        }

        .timer {
            display: inline-block;
            margin-left: 10px;
            color: #f56c6c;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="content-container">
            <div class="header">
                <div class="breadcrumb">您正在做的业务是:人力资源管理--薪酬标准管理--薪酬标准登记复核</div>
                <el-button type="primary" v-on:click="goToAddPage">复核通过</el-button>
                <el-button type="primary" onclick="history.back()">返回</el-button>
            </div>
            <table class="solid-table">
                <tr>
                    <td class="bj">薪酬标准编号</td>
                    <td class="kuan"><input style="width:100%" v-model="Dig" readonly="readonly" /></td>
                    <td class="bj">薪酬标准名称</td>
                    <td class="kuan"><input style="width:100%" v-model="xc_name" /></td>
                    <td class="bj">薪酬总额</td>
                    <td class="kuan"><input style="width:100%" v-model="ze" /></td>
                    <td class="bj"></td>
                </tr>
                <tr>
                    <td class="bj">制定人</td>
                    <td class="kuan"><input style="width:100%" v-model="zdr" /></td>
                    <td class="bj">复核人</td>
                    <td class="kuan"><input style="width:100%" v-model="djr" readonly="readonly" /></td>
                    <td class="bj">登记时间</td>
                    <td class="kuan">
                        <input style="width:calc(100%); display: inline-block;" v-model="djsj" />
                    </td>
                    <td class="bj"></td>
                </tr>
                <tr>
                    <td class="bj">复核意见</td>
                    <td colspan="6">
                        <select style="width:100%;height:50px" v-model="fhyj">
                            <option>同意</option>
                            <option>不同意</option>
                        </select>
                        
                    </td>
                </tr>
                @if (ViewBag.list2 == "aaa")
                {
                    <tr>
                        <td class="bj">序号</td>
                        <td class="bj" colspan="2">薪酬项目名称</td>
                        <td class="bj" colspan="4">金额</td>
                    </tr>
                    <tbody id="employee-table-body">
                        @foreach (var item in ViewBag.list)
                        {
                            <tr>
                                <td>@item.sdt_id</td>
                                <td colspan="2">@item.item_name</td>
                                <td colspan="4">
                                    <input value="@item.salary"
                                           v-on:click="dj"
                                           v-on:input="jd"
                                           data-id="@item.sdt_id" />
                                </td>
                            </tr>
                        }
                    </tbody>
                }

            </table>
        </div>
    </div>

    <script>
        // 定义一个辅助函数用于解码UTF-8字符串
        function decodeUtf8(encodedStr) {
            // 处理URI编码的情况
            if (encodedStr.includes('%')) {
                return decodeURIComponent(encodedStr);
            }

            // 处理普通字符串情况
            return encodedStr;
        }

        // 去除字符串两端的引号
        function removeQuotes(str) {
            if (str && typeof str === 'string') {
                // 移除开头的引号
                if (str.startsWith('"')) {
                    str = str.substring(1);
                }
                // 移除结尾的引号
                if (str.endsWith('"')) {
                    str = str.substring(0, str.length - 1);
                }
            }
            return str;
        }

        // 格式化日期时间为YYYY-MM-DD HH:MM:SS格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        const { createApp, ref, reactive } = Vue;

        const app = createApp({
            setup() {
                const salaries = reactive({});
                const initializeData = () => {
                    const inputs = document.querySelectorAll('#employee-table-body input');
                    inputs.forEach(input => {
                        const id = input.dataset.id;
                        salaries[id] = parseFloat(input.value) || 0;
                    });
                };

                // 使用JSON序列化和反序列化来确保正确传递中文
                const tableData = ref([]);
                const ze = ref(@Model.salary_sum);
                const ze1 = ref(0.00);
                const Dig = ref('@Model.standard_id');
                const ze_name = ref();
                // 修改这两行，添加removeQuotes函数处理
                const xc_name = ref(removeQuotes(decodeUtf8('@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.standard_name, true))')));
                const zdr = ref(removeQuotes(decodeUtf8('@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.designer, true))')));

                const djr = ref('@Context.Session.GetString("UPName")'); // 示例值，实际应从会话获取
                // 修改为精确到秒的格式
                const djsj = ref(formatDateTime(new Date()));
                const fhyj = ref();

                // 计时器相关变量
                const isTimerRunning = ref(true); // 默认自动开始计时
                let timerInterval = null;
                let startTime = null;
                let elapsedTime = 0;

                // 格式化计时器显示
                function formatTimer(seconds) {
                    const h = Math.floor(seconds / 3600);
                    const m = Math.floor((seconds % 3600) / 60);
                    const s = seconds % 60;

                    return [
                        h.toString().padStart(2, '0'),
                        m.toString().padStart(2, '0'),
                        s.toString().padStart(2, '0')
                    ].join(':');
                }

                // 开始计时器
                const startTimer = () => {
                    startTime = new Date().getTime() - elapsedTime;
                    timerInterval = setInterval(() => {
                        const currentTime = new Date().getTime();
                        elapsedTime = currentTime - startTime;
                        const seconds = Math.floor(elapsedTime / 1000);

                        // 同时更新djsj的值为当前精确时间
                        djsj.value = formatDateTime(new Date());
                    }, 1000);
                    isTimerRunning.value = true;
                };

                

                // 调试输出
                // console.log('初始化数据:');
                // console.log('标准编号:', Dig.value);
                // console.log('标准名称:', xc_name.value);
                // console.log('制定人:', zdr.value);
                // console.log('登记人:', djr.value);

                const a = ref(0);
                function dj(event) {
                    const currentValue = parseFloat(event.target.value) || 0;
                    ze1.value = currentValue;
                }

                function jd(event) {
                    const currentValue = parseFloat(event.target.value) || 0;
                    const previousTotal = parseFloat(ze.value) || 0;
                    salaries[event.target.dataset.id] = currentValue;
                    console.info(salaries[event.target.dataset.id])
                    if(currentValue != 0 && event.srcElement.name != ze_name.value && a.value != 0){
                        ze.value = (previousTotal + currentValue).toFixed(2);
                    }else if(event.srcElement.name == ze_name.value && a.value != 0){
                        ze.value = (previousTotal - ze1.value + currentValue).toFixed(2);
                    }else{
                        ze.value = (previousTotal - ze1.value + currentValue).toFixed(2);
                        a.value = a.value + 1;
                    }
                    ze1.value = currentValue;
                    ze_name.value = event.srcElement.name;
                    console.info("当前值:", currentValue, "总计:", ze.value);
                }

                const goToAddPage = () => {
                    ElementPlus.ElMessageBox.confirm(
                        `确定通过吗？`,
                        '是否通过',
                        {
                            confirmButtonText: '通过',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                    .then(() => {
                        insertTitle();
                    })
                    .catch(() => {
                        ElementPlus.ElMessage.info('已取消添加');
                    });
                };

                function insertTitle() {
                    if(xc_name.value === undefined || ze.value === undefined || djr.value === undefined || djsj.value === undefined || fhyj.value === undefined ){
                        ElementPlus.ElMessage.error('不能为空');
                        return null;
                    }

                    // 准备额外项目数据
                    axios.post(`/SS_Server/Update`, null, {
                        params: {
                            Dig: Dig.value,
                            XC_name: xc_name.value,
                            ZE: ze.value,
                            ZDR: zdr.value,
                            DJR: djr.value,
                            DJSJ: new Date(djsj.value).toISOString(),
                            BZ: fhyj.value,
                            // 注意：这里需要定义extraItems变量
                            extraItems: JSON.stringify(salaries)
                        }
                    })
                    .then(res => {
                        console.info(res.data);
                        if(res.data.fh > 0){
                            parent.mainFrame.location.href='@Url.Action("Index", "SS_Server")';
                            ElementPlus.ElMessage.success('复核成功');
                        }else{
                            ElementPlus.ElMessage.error('复核失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.info(err);
                        ElementPlus.ElMessage.error('网络错误，请重试');
                    });
                }

                const getSalaryData = () => {
                    return salaries;
                };

                // 初始化
                Vue.onMounted(() => {
                    initializeData();
                    // 初始更新一次时间
                    djsj.value = formatDateTime(new Date());
                    // 自动开始计时
                    startTimer();
                });

                // 组件卸载时清理计时器
                Vue.onUnmounted(() => {
                    if (timerInterval) {
                        clearInterval(timerInterval);
                    }
                });

                return {
                    tableData,
                    goToAddPage,
                    jd,
                    ze,
                    Dig,
                    xc_name,
                    zdr,
                    djr,
                    djsj,
                    fhyj,
                    dj,
                    getSalaryData,
                    isTimerRunning,
                }
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>
